package com.example.springboot01.utils;

import org.modelmapper.ModelMapper;
import org.modelmapper.convention.MatchingStrategies;

import java.util.ArrayList;
import java.util.List;

/**
 * ModelMapper工具类
 * @author developer
 * @since 2022-5-10
 */
public class ModelMapperUtils {
	
	private static ModelMapper modelMapper = new ModelMapper();
	
	static {
		// 严格匹配策略，源对象和目标对象属性要完全匹配，才能转化
		modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
	}

	/**
	 * 将来源对象转换为目的对象
	 * @param source 来源对象
	 * @param destinationType 目的类
	 * @return 目的对象
	 */
	public static <T> T map(Object source, Class<T> destinationType) {
		
		if (source == null) {
			return null;
		}
		
		return (T) modelMapper.map(source, destinationType);
	}

	/**
	 * 对象转换
	 * @param source 来源对象
	 * @param destination 目的对象
	 */
	public static void map(Object source, Object destination) {
		
		if (source == null) {
			return;
		}
		
		modelMapper.map(source, destination);
	}

	/**
	 * 将列表做转换
	 * @param sourceList 来源列表
	 * @param destinationType 目的列表元素类型
	 * @return 目的列表
	 */
	public static <T> List<T> mapList(List<?> sourceList, Class<T> destinationType) {

		if (sourceList == null || sourceList.isEmpty()) {
			return null;
		}
		List<T> destinationList = new ArrayList<>();
		for (Object source: sourceList){
			T dest = modelMapper.map(source, destinationType);
			destinationList.add(dest);
		}
		return destinationList;
	}
}
